package lzzsrj.union.message.redis;

import lzzsrj.union.message.common.constant.MessageConstants;
import lzzsrj.union.message.redis.listener.RedisMQListener;
import lzzsrj.union.message.redis.listener.RedisMQListenerMethod;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

@Component
public class RedisListenerScanAnnotationProcessor implements BeanPostProcessor {

    public static final List<RedisMQListenerMethod> redisMQListenerMethodList = new ArrayList<>();

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        Class<?> clazz = bean.getClass();
        Method[] methods = clazz.getDeclaredMethods();
        for (Method method : methods) {
            if (method.isAnnotationPresent(RedisMQListener.class)) {
                RedisMQListener annotation = method.getAnnotation(RedisMQListener.class);
                RedisMQListenerMethod redisMQListenerMethod = new RedisMQListenerMethod();
                redisMQListenerMethod.setBean(bean);
                redisMQListenerMethod.setTargetMethod(method);
                redisMQListenerMethod.setBeanName(beanName);
                redisMQListenerMethod.setQuantity(annotation.quantity());
                redisMQListenerMethod.setInterval(annotation.interval());
                redisMQListenerMethod.setTopic(MessageConstants.RedisMessage.PREFIX_REDIS_MESSAGE + annotation.topic());
                redisMQListenerMethod.setMethodParameterClassName(method.getParameterTypes()[0].getName());
                redisMQListenerMethodList.add(redisMQListenerMethod);
            }
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
    }

    public static List<RedisMQListenerMethod> getRedisMQListenerMethodList() {
        return redisMQListenerMethodList;
    }
}